<template>
  <div class="app-container">
    <local-loading :loading="loading"></local-loading>
    <div class="search-container">
      <el-form :inline="true" label-position="left">
        <el-form-item prop="keywords" :label="$t('task.Aufgabenname')">
          <el-input
            v-model="queryParams.keywords"
            auto-insert-space
            :placeholder="$t('task.BitteAufgabennamen')"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="$t('task.Zustand')">
          <el-select v-model="queryParams.status">
            <el-option
              v-for="dict in experiment_status_type"
              :key="dict.value"
              :label="
                translateTagDictI18n('experiment_status_type', dict.label)
              "
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-throttle="handleQuery" type="primary"
            ><el-icon style="margin-right: 5px; font-size: 18px">
              <Search /> </el-icon
            >{{ $t("task.Suche") }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button v-throttle="resetting" type=""
            ><el-icon style="margin-right: 5px; font-size: 18px">
              <Refresh /> </el-icon
            >{{ $t("task.Zurücksetzen") }}</el-button
          >
        </el-form-item>

        <el-button
          v-throttle="publishtask"
          v-hasPerm="['courseinfo:task:add']"
          class="CirclePlus"
          type="success"
          ><el-icon> <CirclePlus /> </el-icon>&nbsp;
          {{ $t("task.AufgabeVeröffentlichen") }}</el-button
        >
      </el-form>
    </div>

    <el-row v-if="experimentList?.length != 0 && !loading" :gutter="30">
      <el-col
        v-for="(item, index) in experimentList"
        :key="index"
        :span="8"
        style="margin-top: 10px"
      >
        <el-card class="box-card" :body-style="{ padding: '0px' }">
          <template #header>
            <div class="card-header">
              <span style="font-size: 1.2rem"
                >{{ $t("task.Aufgabenname") }}: {{ item.name }}</span
              >
              <el-dropdown>
                <el-button
                  v-hasPerm="['courseinfo:task:edit', 'courseinfo:task:delete']"
                  link
                  style="padding-bottom: 1px; font-size: 1rem"
                  class="btnlink"
                  ><el-icon> <Setting /> </el-icon>&nbsp;{{
                    $t("task.Betrieb")
                  }}</el-button
                >
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="edit(item.id)">{{
                      $t("task.bearbeiten")
                    }}</el-dropdown-item>
                    <el-dropdown-item @click="remove(item.id)">{{
                      $t("task.löschen")
                    }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <template #default>
            <div class="text item" @click="correct(item.id)">
              <p style="font-size: 1rem; padding: 0; margin: 10px 0 0 0">
                {{ $t("task.Startzeit") }}：{{ item.startTime }}
              </p>
              <p style="font-size: 1rem; padding: 0; margin: 10px 0 0 0">
                {{ $t("task.Kündigungszeit") }}：{{ item.endTime }}
              </p>
              <p style="font-size: 1rem; padding: 0; margin: 10px 0 0 0">
                {{ $t("task.VerantwortungsbewussterLehrer") }}：{{
                  item.leader
                }}
              </p>
              <p
                style="
                  font-size: 1rem;
                  padding: 0;
                  margin: 10px 0 0 0;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
              >
                {{ $t("task.ProfessorKlasse") }}：{{ item.classes.toString() }}
              </p>
              <p style="font-size: 1rem; padding: 0; margin: 10px 0 0 0">
                {{ $t("task.Aufgabenstatus") }}：<el-tag
                  :type="
                    item.status == 0
                      ? 'success'
                      : item.status == -1
                      ? 'info'
                      : item.status == 2
                      ? 'warning'
                      : 'danger'
                  "
                  class="mx-1"
                  effect="dark"
                >
                  {{ $t("task." + item.statusLabel) }}
                </el-tag>
              </p>
            </div>

            <el-divider style="margin: 7px 0" />
            <div class="tj">
              <span
                style="
                  font-size: 1.2rem;
                  color: var(--el-color-primary);
                  font-weight: bold;
                "
                >{{ $t("task.EingereichtL") }}：{{ item.submit }}/{{
                  item.total
                }}</span
              >
              <span
                style="
                  font-size: 1.2rem;
                  color: var(--el-color-primary);
                  font-weight: bold;
                "
                >{{ $t("task.Korrigiert") }}：{{ item.correct }}/{{
                  item.submit
                }}</span
              >
            </div>
          </template>
        </el-card>
      </el-col>

      <!-- 分页 -->
    </el-row>
    <empty-state v-else :name="$t('task.Derzeitverfügbar')"></empty-state>
    <pagination
      v-if="total > 0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />
    <back-top></back-top>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Task",
  inheritAttrs: false,
});
import { getExperimentPage, deleteTask } from "@/api/task";
import {
  CourseExperimentPageVO,
  CourseExperimentQuery,
} from "@/api/task/types";
import LocalLoading from "@/components/LocalLoading/index.vue";
import EmptyState from "@/components/EmptyState/index.vue";
import BackTop from "@/components/BackTop/index.vue";
import { useAppStore } from "@/store/modules/app";
import { translateTagDictI18n } from "@/utils/i18n";
import { useRoute, useRouter } from "vue-router";
import { useCourseStore } from "@/store/modules/course";

const courseStore = useCourseStore();
const router = useRouter();
// 字典
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { experiment_status_type } = proxy?.useDict("experiment_status_type"); // 状态信息
// 汉堡
const appStore = useAppStore();
// 任务列表总数
const experimentList = ref<CourseExperimentPageVO[]>();
const total = ref(0);
const loading = ref(true);
const courseId = ref();
// 获取课程请求数据
const queryParams = reactive<CourseExperimentQuery>({
  pageNum: 1,
  pageSize: 10,
});

function correct(experimentId: number) {
  let routeData = router.resolve({
    path: "/correctinfo",
    query: {
      experimentId: experimentId,
      courseId: courseId.value,
    },
  });
  window.open(routeData.href, "_blank");
}

// 查询所有任务列表数据
const handleQuery = () => {
  total.value = 0;
  loading.value = true;
  getExperimentPage(queryParams, courseId.value)
    .then(({ data }) => {
      experimentList.value = data.list;
      total.value = data.total;
    })
    .catch(() => {
      loading.value = true;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 重置表单
function resetting() {
  queryParams.keywords = "";
  queryParams.status = "" as unknown as number; // 将未知类型转换成number
  handleQuery();
}
// 删除任务函数
function remove(experimentId: number) {
  ElMessageBox.confirm("确认删除此任务?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteTask(experimentId)
      .then(() => {
        handleQuery(); // 刷新
        ElMessage.success("删除任务成功");
      })
      .catch((err) => {
        console.log(err);
      });
  });
}

// 编辑
function edit(experimentId: number) {
  // 打开弹窗信息
  courseStore.editSaveExp(experimentId).then(() => {
    router.push({
      path: "/courseinfo/editask",
      query: {
        experimentId,
      },
    });
  });
}

/**
 * （添加任务）
 */
function publishtask() {
  router.push({
    path: "/courseinfo/addtask",
  });
}

// // 监听当前路由的name变化
watch(
  () => router.currentRoute.value.name,
  (newRouterName: any, oldRouterName: any) => {
    if (
      (oldRouterName === "Editask" || oldRouterName === "Addtask") &&
      newRouterName === "Task"
    ) {
      handleQuery();
    }
  },
  { immediate: true }
);

onMounted(() => {
  courseId.value = courseStore.courseId;
  // 隐藏展板
  handleQuery();
});
</script>

<style scoped lang="scss">
.CirclePlus {
  position: absolute;
  /* 绝对定位，相对于最近的定位祖先元素 */
  right: 40px;

  font-weight: bolder;

  .el-icon {
    font-size: 16px;
  }
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.el-dropdown {
  border-style: none;

  &:hover {
    border-style: none;
  }
}

.btnlink {
  --el-button-outline-color: none;
  border-style: none;

  &:hover {
    border-style: none;
  }

  &:focus {
    border-style: none;
  }
}

.tj {
  padding: 0px 20px 10px 20px;
  font-size: 14px;
  color: #808080;
  display: flex;
  justify-content: space-between;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bolder;
  padding: 0;
  margin: 0;
}

.text {
  padding: 0rem 20px;
  font-size: 14px;
  cursor: pointer;
}

.box-card {
  background: var(--el-bg-color-overlay);
}

:deep(el-card__header) {
  padding: 10px 20px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}
</style>
